import 'package:acgn_pioneer/models/base_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../public.dart';

mixin CreditMixin<S extends StatefulWidget> on State<S> {
  RefreshController _refreshController = RefreshController();
  Map<String, dynamic> userScore = {
    'pager': PagerModel.fromJson({}),
    'data': []
  };
  UserProvider user;
  bool isInitLoaded = false;

  Future getUserScore([int type = 0]) {
    int page = userScore['pager'].page + 1;
    return Future.delayed(Duration(milliseconds: 3), () {
      return UserService.getUserScore(
              {'overdue': type, 'page': page, 'size': userScore['pager'].size})
          .then((res) {
        userScore['data'].addAll(res.data);
        // 修复服务端返回page为总页数，这里我们需要的是当前页码
        res.pager.page = page;
        int total = res.pager.total ?? 0;
        if (total <= page * res.pager.size) {
          _refreshController.loadNoData();
        } else {
          userScore['pager'] = res.pager;
          _refreshController.loadComplete();
        }
        isInitLoaded = true;
        setState(() {});
        return res;
      }).catchError((err) {
        isInitLoaded = true;
        setState(() {});
        _refreshController.loadFailed();
      });
    });
  }

  void requestHanddle() {
    getUserScore();
  }

  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  Widget commonBuild(BuildContext context) {
    int len = userScore['data'].length;
    return RefreshConfig(
        child: SmartRefresher(
            enablePullDown: false,
            enablePullUp: isInitLoaded && len > 0,
            controller: _refreshController,
            onLoading: requestHanddle,
            onRefresh: () async {
              await getUserScore();
              _refreshController.refreshCompleted();
            },
            child: isInitLoaded
                ? (len > 0
                    ? ListView.builder(
                        shrinkWrap: true,
                        itemCount: len,
                        itemBuilder: (BuildContext context, index) {
                          return _getItem(userScore['data'][index]);
                        })
                    : EmptyComponent())
                : LoadingComponent()));
  }

  Widget _getItem(item) {
    return Container(
        padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
        child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text(item.desc,
                    style: TextStyle(
                        fontSize: 14, height: 1.75, color: Colors.white)),
                Text(
                    '${StringUtil.formatDate(item.createdTime, 'yyyy.MM.dd')} ~ ${StringUtil.formatDate(item.expireTime, 'yyyy.MM.dd')}',
                    style: TextStyle(
                        fontSize: 12,
                        height: 1.5,
                        color: ColorUtil.rgba(255, 255, 255, 0.6)))
              ]),
              Column(children: [
                Text(
                  '${item.gotNum}',
                  style: TextStyle(fontSize: 16, color: Colors.yellow),
                )
              ]),
            ]));
  }
}
